package com.example.glgk.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * @author liuxingkun
 * <p>用于替换字符串中#{}为实际值的工具类</p>
 */
public class StringReplaceUtils {

    public static String replacePlaceholders(String originalString, String[] replacementData) {
        // 使用StringBuilder来构建替换后的字符串
        StringBuilder result = new StringBuilder(originalString);

        // 查找第一个占位符的索引
        int startIndex = result.indexOf("#{}");

        // 遍历replacementData数组，用其中的数据逐个替换占位符
        int dataIndex = 0;
        while (startIndex != -1 && dataIndex < replacementData.length) {
            String replacement = replacementData[dataIndex];
            if(StringUtils.isNoneBlank(replacement)){
                // 替换占位符
                result.replace(startIndex, startIndex + 3, replacement);

                // 查找下一个占位符的索引
                startIndex = result.indexOf("#{}");
            }

            // 增加replacementData数组的索引
            dataIndex++;
        }

        return result.toString();
    }
}
